package com.vshop.timingtask;

import com.alibaba.fastjson.JSON;
import com.vshop.entity.comentity.PartnerInfo;
import com.vshop.entity.newpojo.TurntoInterfaceUtils;
import com.vshop.entity.newpojo.request.RequestBody.SynchronousPartnerRequestBody;
import com.vshop.entity.newpojo.request.RequestHeader;
import com.vshop.entity.newpojo.request.subRequest.SynchronousPartnerRequest;
import com.vshop.entity.newpojo.response.subResponse.SynchronousPartnerResponse;
import com.vshop.entity.newpojo.response.subResponse.common._Partner;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.syncpartner.request.RequestSyncPartner;
import com.vshop.entity.requestinterface.syncpartner.response.ResponseSyncPartner;
import com.vshop.service.PartnerInfoService;
import com.vshop.utils.HttpClientTool;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.JaxbUtil;
import com.vshop.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 北京给深圳内部使用的同步企业的接口:2.0接口
 *
 * @author lm
 * @date 2019/5/23
 */

@Configuration
@EnableScheduling
@RestController
@Slf4j
public class SyncPartnerTask {
    @Value("${xmlIot.BASE_URL}")
    private String BASE_URL;
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    PartnerInfoService partnerService;

    //@Scheduled(cron = " 0 2 19 * * ?")
    @Async
    @GetMapping(value = "syncPartner")

    public void execute() {
        if (autoTask) {
            syncPartner();
        }
    }

    public void syncPartner() {
        try {
            log.info("每1天早上19点执行一次的syncPartner开始执行！");
            RequestSyncPartner sync = new RequestSyncPartner();
            sync.setPageNo(1);
            sync.setPageSize(1);

            String requestInterface = JSON.toJSONString(sync);
            String url = "http://localhost:8085/iot" + Constant.iot_syncPartner;
            String returnStr = HttpUtil.httpPost(url, requestInterface);
            ResponseSyncPartner response = JSON.parseObject(returnStr, ResponseSyncPartner.class);

            if (response != null && response.getPage() != null) {

                int totalCount = response.getPage().getTotalCount();

                if (totalCount > 0) {

                    double total;

                    if (Math.ceil(totalCount / 1000) < 1) {
                        total = 1;
                    } else {
                        total = Math.ceil(totalCount / 1000) + 1;
                    }

                    for (int x = 1; x <= total; x++) {

                        log.info("totalCount是：" + totalCount + ";total是：" + total + ";x是：" + x);

                        // 请求参数拼接
                        SynchronousPartnerRequest request = new SynchronousPartnerRequest();
                        TurntoInterfaceUtils utils = new TurntoInterfaceUtils();
                        RequestHeader header = utils.getRequestHeader(Constant.cmd_queryPartnerSync, "GMSYS");
                        request.setHeader(header);

                        SynchronousPartnerRequestBody body = new SynchronousPartnerRequestBody();
                        body.setPageNo(Integer.toString(x));
                        body.setPageSize("1000");

                        request.setBody(body);

                        String sign = utils.getSign(header, body, body.getClass(), "wORfzY1DbaB39RJ4s82QxGs8bSGfeU8z");
                        request.setSign(sign);

                        // 将参数转换成XML格式
                        String sRequest = new JaxbUtil(SynchronousPartnerRequest.class).toXml(request, "utf-8");
                        log.info("【syncPartner】请求：" + sRequest);

                        String result = HttpClientTool.sendHttpPost(BASE_URL, sRequest);
                        log.info("【syncPartner】响应：" + result);
                        SynchronousPartnerResponse responseObj = new JaxbUtil(SynchronousPartnerResponse.class).fromXml(result, "utf-8");

                        // 返回错误结果的处理
                        String retCode = responseObj.getHeader().getResultCode();

                        if (Constant.RET_CODE_0000.equalsIgnoreCase(retCode)) {

                            List<_Partner> partnerList = responseObj.getBody().getPartner();

                            for (_Partner p : partnerList) {

                                String partnerCode = p.getPartnerCode();
                                Integer partnerIndex = 0;

                                if (!partnerCode.equals("0")) {
                                    partnerIndex = Integer.parseInt(partnerCode.substring(2)) % 10;
                                }
                                String token = MD5.calcMD5(p.getPartnerName() + p.getPartnerCode() + p.getSecret());

                                //先去数据库查询partnerCode是不是已经存在
                                int count = partnerService.findPartnerCodeEixtOrNot(partnerCode);

                                if (count <= 0) {
                                    PartnerInfo partner = new PartnerInfo();
                                    partner.setPartnerIndex(String.valueOf(partnerIndex));
                                    partner.setPartnerName(p.getPartnerName());
                                    partner.setPartnerCode(partnerCode);
                                    partner.setSecret(p.getSecret());
                                    partner.setToken(token);
                                    partner.setPartnerGrade(p.getPartnerType());
                                    partner.setPartnerHeader(p.getConnector());
                                    partner.setPartnerPhone(p.getPhoneNum());
                                    partner.setPartnerEmail(p.getEmail());
                                    partner.setCompanylogo("https://wx.linksfield.net/upload/logo/logo.png");
                                    partnerService.insertPartner(partner);

                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                }
            }
            log.info("每1天晚上19点执行一次的syncPartner执行完毕！");
        } catch (Exception e) {
            log.info("syncPartner捕获到异常：" + e);
        }
    }

}
